package org.dingfugui.triple.link;

import org.dingfugui.triple.connection.Connection;
import org.dingfugui.triple.connection.ConnectionFactory;
import org.dingfugui.triple.link.zk.RemoteServer;
import org.dingfugui.triple.link.zk.RemoteServerMetaData;
import org.dingfugui.triple.link.zk.ZookeeperConnection;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 注册中心连接
 *
 * @author fugui.ding at 2015/6/12
 */
public abstract class RegistrationLink extends AbstractLink {

    protected Map<RemoteServerMetaData, Queue<ZookeeperConnection>> conMap = new ConcurrentHashMap<>();

    protected List<RemoteServer> remoteServers = new ArrayList<>();
    protected int next;
    protected ReadWriteLock lock = new ReentrantReadWriteLock();


    public RegistrationLink(String host, ConnectionFactory factory) {
        super(host, factory);
    }

    public RegistrationLink(String host, int port, ConnectionFactory factory) {
        super(host, port, factory);
    }

    @Override
    public Connection getConnection() {
        lock.readLock();

        if (next == 0 || next > remoteServers.size()) {
            next = 1;
        }

        RemoteServer server = remoteServers.get(0);

        Connection con = server.getQueue().poll();
        if (con != null) {
            return con;
        }


        return null;
    }

}
